<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input id="uid" placeholder="请输入用户id"/><br>
<button onclick="onConnectClick();">点击连接服务器</button>
<script>
    let socket;
    function onConnectClick(){
        if(typeof(WebSocket)=="undefined"){
            console.log("浏览器不支持websocket");
        }else{
            console.log("浏览器支持websocket");
            let uid=document.getElementById("uid").value;
            let webSocketUrl="ws://localhost:9001/webSocket/"+uid;
            if(socket!=null){
                socket.close();
                socket=null;
            }
            //socket一定是null
            //跟服务器创建连接
            socket=new WebSocket(webSocketUrl);

            socket.onopen=function(){
                console.log("websocket打开");
            };
            socket.onmessage=function(msg){
                console.log("接到数据："+msg.data);
                let result=msg.data;
                if(result.init==1){
                    //刚刚连接后初始化的数据
                    //应该是一个jsonarray
                    let msgs=result.messages;
                }else{
                    //实时推送的数据
                    //应该是一个jsonobject
                    //直接操作result
                }
            };
            socket.onclose=function(){
                console.log("websocket关闭");
            };
            socket.onerror=function(){
                console.log("websocket发生异常");
            };
        }
    }

</script>
</body>
</html>